package integrity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class VerifyKey {

	/**
	 * @param args
	 * @throws Exception 
	 * @throws Exception 
	 */
	public static boolean VerifyFile() throws Exception {
		
		//Generating the assymetric secret key
				KeyGenerator kg = KeyGenerator.getInstance("AES");
				kg.init(128);
				SecretKey k = kg.generateKey();

		//System.out.println("Checking Encrypted folder for publicKey..");
		//Loading the Public key from the Encrypted folder
		FileInputStream publicKeyLoad = new FileInputStream("PublicKey.publickey");
		byte[] encKey = new byte[publicKeyLoad.available()];  
		publicKeyLoad.read(encKey);
		
		X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
		//Using the RSA keyfactory
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
		
		//System.out.println("Getting the signedFile...");
		FileInputStream signedFileInput = new FileInputStream("credentials_signed.txt");
		
		byte[] signatureToVerify = new byte[signedFileInput.available()];
		signedFileInput.read(signatureToVerify);
		signedFileInput.close();
		
		//System.out.println("Verifying the signedFile with the publicKey");
		//Verifying the signed file
		Signature sig = Signature.getInstance("SHA1withRSA");
		sig.initVerify(pubKey);
		
		FileInputStream enctryptedFileLoad = new FileInputStream("credentials.txt");
		
		BufferedInputStream bufin = new BufferedInputStream(enctryptedFileLoad);

		byte[] buffer = new byte[1024];
		int len;
		while (bufin.available() != 0) {
		    len = bufin.read(buffer);
		    sig.update(buffer, 0, len);
		};

		bufin.close();
		boolean verfication = sig.verify(signatureToVerify);
		
		return verfication;
	}

}
